package edu.jsnu.service.ticket.order.service.impl;

import beans.PageQuery;
import com.github.pagehelper.PageHelper;
import edu.jsnu.service.ticket.order.dao.OrderMapper;
import edu.jsnu.service.ticket.order.domain.Order;
import edu.jsnu.service.ticket.order.dto.OrderShow;
import edu.jsnu.service.ticket.order.service.OrderService;
import edu.jsnu.service.ticket.seat.dao.SeatMapper;
import edu.jsnu.service.ticket.user.dao.UserMapper;
import edu.jsnu.service.ticket.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@EnableScheduling
@Service("orderServiceManager")
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SeatMapper seatMapper;

    @Override
    public List<OrderShow> getAllOrder(PageQuery pageQuery) {
        PageHelper.startPage(pageQuery.getPage(), pageQuery.getLimit());
        List<OrderShow> orderList = orderMapper.getAllOrder();
        return orderList;
    }

    @Override
    public OrderShow getOrderInfoById(Integer id) {
        OrderShow order = orderMapper.selectOrderById(id);
        return order;
    }

    //管理员更新用户订单状态
    @Override
    public Integer updateOrderStatusByAdmin(Integer id, Integer status) {
        //改变用户订单状态

        orderMapper.updateOrderStatus(id, 2);
        //根据订单id取得当前订单
        Order order = orderMapper.selectByPrimaryKey(id);
        //取得用户
        User user = userMapper.selectByPrimaryKey(order.getUserId());
        //退还用户的费用
        if (user != null)
        user.setBalance(user.getBalance() + order.getMoney());
        //写入数据库
        Integer result = userMapper.updateByPrimaryKey(user);
        //删除座位信息
        seatMapper.deleteByOrderId(id);
        return result;
    }

    //订单时间检测定时器，前台如何显示剩余时间？
    //每隔一分钟取数据库下单时间与现在时间对比
//    @Scheduled(cron = "0 */1 * * * ?")
    public void closeOrder(){
        //取得所有未支付订单
        Integer status = 0;
        List<Order> orders = orderMapper.getAllOrderByStatus(status);
        //取得订单生成时间与当前时间对比是否超过15分钟
        final long fifteenMintus = 15 * 60 * 1000;

        if(orders != null && !orders.isEmpty()){
            for(Order o : orders){
                if (new Date().getTime() - o.getOrderTime().getTime() > fifteenMintus){
                    //如果超过15分钟修改订单状态为2
                    o.setStatus(2);
                    orderMapper.updateByPrimaryKey(o);
                }
            }
        }

    }
}
